<template>
  <NavBar></NavBar>
  <div id="container"></div>
<!--  前面是地图，后面是肉牛详情页面-->
  <el-dialog v-model="dialogVisible" title="肉牛详情" width="30%">
    <div v-if="selectedCattle" class="cattle-detail">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-image
              :src="selectedCattle.photo"
              class="cattle-avatar"
              fit="cover"
          />
        </el-col>
        <el-col :span="16">
          <div class="detail-item">
            <span class="label">名称：</span>
            <span class="value">{{ selectedCattle.name }}</span>
          </div>
          <div class="detail-item">
            <span class="label">体温：</span>
            <span class="value">{{ selectedCattle.temperature || '暂无' }}℃</span>
            <el-button type="text" @click="viewHistory('temperature')">历史</el-button>
          </div>
          <div class="detail-item">
            <span class="label">速度：</span>
            <span class="value">{{ selectedCattle.speed || 0 }}cm/s</span>
          </div>
          <div class="detail-item">
            <span class="label">方向：</span>
            <span class="value">{{ selectedCattle.direction || 0 }}°</span>
          </div>
          <div class="detail-item">
            <span class="label">体重：</span>
            <span class="value">{{ selectedCattle.initialWeight }}kg</span>
            <el-button type="text" @click="viewHistory('weight')">历史</el-button>
          </div>
          <div class="detail-item">
            <span class="label">喂食状态：</span>
            <el-tag :type="selectedCattle.isFeed ? 'success' : 'danger'">
              {{ selectedCattle.isFeed ? '已喂食' : '未喂食' }}
            </el-tag>
          </div>
          <!-- 新增位置信息 -->
          <div class="detail-item">
            <span class="label">当前位置：</span>
            <span class="value">{{ selectedCattle.latitude ? `${selectedCattle.latitude}, ${selectedCattle.longitude}` : '暂无' }}</span>
            <el-button type="text" @click="viewHistory('location')">历史</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
  </el-dialog>
</template>

<script>
import {ref, onMounted, nextTick} from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { computed } from 'vue'
import { watch } from 'vue'
import NavBar from "@/components/NavBar.vue";
import router from "@/router";

export default {
  components: {NavBar},
  setup() {
    const store = useStore()
    const map = ref(null)
    const cattleList = computed(() => store.state.cattle.cattleList)
    const selectedCattle = ref(null)
    const dialogVisible = ref(false)

    // 安徽工业大学经纬度（示例坐标）
    const defaultPoint = { lng: 118.551, lat: 31.673 }

//监听数据变动，更新地图
    watch(
        () => [...store.state.cattle.cattleList], // 创建新数组触发深度监听
        async (newVal, oldVal) => {
          const needUpdate = newVal.some((cattle, index) => {
            // 比对关键数据是否变化
            return cattle.longitude !== oldVal[index]?.longitude ||
                cattle.latitude !== oldVal[index]?.latitude ||
                cattle.photo !== oldVal[index]?.photo
          })

          if (needUpdate) {
            await nextTick() // 等待 DOM 更新
            await addMarkers()
          }
        },
        { deep: true }
    )
    // 创建自定义图标
    const createCustomIcon = (cattle) => {
      return new Promise((resolve) => {
        const size = 80 // 保持这个尺寸与Marker3D的size一致
        const img = new Image()
        img.crossOrigin = "anonymous" // 必须的跨域设置

        img.onload = () => {
          // 创建圆形Canvas
          const canvas = document.createElement('canvas')
          canvas.width = size
          canvas.height = size
          const ctx = canvas.getContext('2d')

          // 绘制圆形遮罩
          ctx.beginPath()
          ctx.arc(size/2, size/2, size/2, 0, Math.PI*2)
          ctx.closePath()
          ctx.clip()

          // 绘制图片
          ctx.drawImage(img, 0, 0, size, size)

          // 创建Icon对象（注意这里不需要设置anchor）
          const icon = new window.BMapGL.Icon(
              canvas.toDataURL(),
              new window.BMapGL.Size(size, size)
          )
          resolve(icon)
        }

        img.onerror = () => {
          console.log("hahaha");
          console.log(cattle.photo)
          // 使用默认头像
          img.src = 'http://localhost:7090/avatar/avatar_3.jpg'
        }

        img.src = cattle.photo || 'http://localhost:7090/avatar/avatar_3.jpg'
      })
    }

    // 添加标记
    const addMarkers = async () => {
      if (!map.value) return

      // 清除旧标记
      map.value.clearOverlays()

      for (const cattle of cattleList.value) {
        console.log(124)
        if (!cattle.longitude || !cattle.latitude) continue

        console.log(cattle.longitude + cattle.latitude + "cattle是" + cattle);
        const point = new window.BMapGL.Point(
            parseFloat(cattle.longitude),
            parseFloat(cattle.latitude)
        )

        try {
          const icon = await createCustomIcon(cattle)

          // 创建3D标记
          const marker = new window.BMapGL.Marker3D(
              point,
              10, // 高度（单位：米）
              {
                size: 80, // 必须与图标尺寸一致
                icon: icon,
                shape: 1 // 强制圆形
              }
          )

          marker.addEventListener('click', () => {
            selectedCattle.value = cattle
            dialogVisible.value = true
          })

          map.value.addOverlay(marker)
        } catch (error) {
          console.error('创建标记失败:', error)
        }
      }
    }

    // 初始化地图
    const initMap = () => {
      const BMapGL = window.BMapGL
      map.value = new BMapGL.Map('container', {
        enableMapClick: false, // 禁用底图POI
        displayOptions: {
          building: true // 隐藏建筑物
        }
      })

      // 设置地图中心点和缩放级别
      map.value.centerAndZoom(
          new BMapGL.Point(defaultPoint.lng, defaultPoint.lat),
          18 // 较大的缩放级别保持标记可见
      )

      // 启用惯性拖拽（提升体验）
      map.value.enableInertialDragging()

      map.value.enableScrollWheelZoom(true)
    }

    // 获取数据
    const fetchData = () => {
      store.dispatch("fetchCattleList", {
        token: store.state.user.token,
        success: async (resp) => {
          // await addMarkers() // 添加await
          console.log(resp)
        },
        error: (err) => {
          ElMessage.error(err.message || '数据获取失败')
        }
      })
    }

    // 生命周期
    onMounted(async () => {
      await nextTick() // 等待DOM更新
      initMap()
      await addMarkers()
      fetchData()
    })

    const viewHistory = (type) => {
      console.log(`查看${type}历史数据`, selectedCattle.value)
      switch(type) {
        case 'temperature':
          router.push({
            path: '/temperature',
            query: { cattleId: selectedCattle.value.id }
          })
          break
        case 'location':
          router.push({
            path: '/location',
            query: { cattleId: selectedCattle.value.id }
          })
          break
        case 'weight':
          router.push({
            path: '/weight',
            query: { cattleId: selectedCattle.value.id }
          })
          break
      }
    }

    return {
      dialogVisible,
      selectedCattle,
      viewHistory
    }
  }
}
</script>

<style scoped>
#container {
  height: calc(100vh - 60px);
  background: #f5f7fa;

}

.cattle-avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 2px solid #fff;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.detail-item {
  margin: 12px 0;
  display: flex;
  align-items: center;
}

.label {
  color: #909399;
  min-width: 70px;
}

.value {
  color: #606266;
  margin-right: 15px;
}

/* 在全局样式中添加 */
</style>